(function(window, angular, undefined){
	angular.module('cesium.draw', [])
	.factory('$cesium_draw',  ["$rootScope", function($rootScope) {
		$cesium_draw = {
			
		};
		for(f in $cesium_draw){
			$rootScope[f] = $cesium_draw[f];
		}
		return $cesium_draw;
	}])
	.run(["$rootScope", "$cesium_draw", function($rootScope, $cesium_draw) {}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.graphic', [])
	.factory('$cesium_graphic',  ["$rootScope", function($rootScope) {
		$cesium_graphic = {
			
		};
		for(f in $cesium_graphic){
			$rootScope[f] = $cesium_graphic[f];
		}
		return $cesium_graphic;
	}])
	.run(["$rootScope", "$cesium_graphic", function($rootScope, $cesium_graphic) {}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.toolbar', [])
	.factory('$cesium_toolbar',  ["$rootScope", function($rootScope) {
		$cesium_toolbar = {
			// 全图
			cesiumFullextent : function(){
				var go = $rootScope.gisObject;
				var e = go.fullExtent;
				if(e){
					$rootScope.setCesiumExtent(e);
				}
			}
		};
		for(f in $cesium_toolbar){
			$rootScope[f] = $cesium_toolbar[f];
		}
		return $cesium_toolbar;
	}])
	.run(["$rootScope", "$cesium_toolbar", function($rootScope, $cesium_toolbar) {}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.utils', [])
	.factory('$cesium_utils',  ["$rootScope", function($rootScope) {
		$cesium_utils = {

			// 获取当前视图范围字符串
			getCesiumExtent : function(){
				var extent = $rootScope.getCurrent3DExtent();
				return extent.xmin + "," + extent.ymin + "," 
						+ extent.xmax + "," + extent.ymax;
			},

			// 获取当前三维范围
			getCurrent3DExtent:function(){
			    // 范围对象
			    var extent = {};
			    // 得到当前三维场景
			    var viewer = $rootScope.gisObject.cesium;
			    var scene = viewer.scene;
			    
			    // 得到当前三维场景的椭球体
			    var ellipsoid = scene.globe.ellipsoid;
			    var canvas = scene.canvas;
			    
			    // canvas左上角
			    var car3_lt = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(0,0), ellipsoid);
			    
			    // canvas右下角
			    var car3_rb = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(canvas.width,canvas.height), ellipsoid);
			    
			    // 当canvas左上角和右下角全部在椭球体上
			    if (car3_lt && car3_rb) {
			        var carto_lt = ellipsoid.cartesianToCartographic(car3_lt);
			        var carto_rb = ellipsoid.cartesianToCartographic(car3_rb);
			        extent.xmin = Cesium.Math.toDegrees(carto_lt.longitude);
			        extent.ymax = Cesium.Math.toDegrees(carto_lt.latitude);
			        extent.xmax = Cesium.Math.toDegrees(carto_rb.longitude);
			        extent.ymin = Cesium.Math.toDegrees(carto_rb.latitude);
			    }
			    
			    // 当canvas左上角不在但右下角在椭球体上
			    else if (!car3_lt && car3_rb) {
			        var car3_lt2 = null;
			        var yIndex = 0;
			        do {
			            // 这里每次10像素递加，一是10像素相差不大，二是为了提高程序运行效率
			            yIndex <= canvas.height ? yIndex += 10 : canvas.height;
			            car3_lt2 = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(0,yIndex), ellipsoid);
			        }while (!car3_lt2);
			        var carto_lt2 = ellipsoid.cartesianToCartographic(car3_lt2);
			        var carto_rb2 = ellipsoid.cartesianToCartographic(car3_rb);
			        extent.xmin = Cesium.Math.toDegrees(carto_lt2.longitude);
			        extent.ymax = Cesium.Math.toDegrees(carto_lt2.latitude);
			        extent.xmax = Cesium.Math.toDegrees(carto_rb2.longitude);
			        extent.ymin = Cesium.Math.toDegrees(carto_rb2.latitude);
			    }
			    
			    // 获取高度
			    extent.height = Math.ceil(viewer.camera.positionCartographic.height);
			    return extent;
			},

			// 设置3D的当前视图范围
			setCesiumExtent:function(e){
				var go = $rootScope.gisObject;
				if(!go.cesium) return;
				var rectangle = new Cesium.Rectangle.fromDegrees(e.xmin, e.ymin, e.xmax, e.ymax);
			 	go.cesium.camera.flyTo({
		        	destination: rectangle
		    	});
			},
			
			identityCes:function(){
			    var handler3D = new Cesium.ScreenSpaceEventHandler(cesium.cesiumViewer.scene.canvas);
			    handler3D.setInputAction(function(movement) {
			        //点击弹出气泡窗口
			        var pick = cesium.cesiumViewer.scene.pick(movement.position);
			        if(pick && pick.id){//选中某模型
			            var cartographic = Cesium.Cartographic.fromCartesian(pick.id._position._value);//世界坐标转地理坐标（弧度）
			            var point=[ cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];//地理坐标（弧度）转经纬度坐标
			            var destination=Cesium.Cartesian3.fromDegrees(point[0], point[1], 3000.0);
			            var content ="<div  style='border-bottom: 1px solid #C6CBCE;'>"+
			                "<span style='margin-left: 5px;'>测试测试1</span>"+
			                "<div id='infoClose3D' class='closeButton' style='margin-right: 4px;'></div>"+
			                "</div>"+                                    
			                "<div>"+
			                "<label>测试1:</label><label>测试1</label></br>"+
			                "<label>测试2:</label><label>测试2</label></br>"+
			                "<label>测试3:</label><label>测试3</label></br>"+
			                "</div>";
			            var obj = {position:movement.position,destination:destination,content:content};
			            cesium.infoWindow(obj);            
			        }
			    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
			},
			
			infoWindow:function(obj){
				var go = $rootScope.gisObject;
				var picked=go.cesium.cesiumViewer.scene.pick(obj.position);
				if(Cesium.defined(picked)){
					var id=Cesium.defaultValue(picked.id,picked.primitive.id);
					if(id instanceof Cesium.Entity){
						if(obj.destination){
							go.cesium.cesiumViewer.Camera.flyTo({
								destination:obj.destination
							});
						}
					}
					
					$(".cesium-selection-wrapper").show();
					$("#infowin3Dcontent").empty();
					$("#infowin3Dcontent").append(obj.content);
					
					if(obj.css && obj.css.width){
						$(".infowin3D").css("width", obj.css.width);
					}
					
					if(obj.css && obj.css.height){
						$(".infowin3D").css("width", obj.css.height);
						$(".infowin3D").css("margin-top", -($(".infowin3D").height()-30));
						$(".arrow").css("left",($(".infowin3D").width()/2-20));
						$(".infowin3D").css("margin-left",-($(".infowin3D").width()/2-76));
		                $(".infowin3D").show();
		                $("#infoClose3D").click(function () {
		                    $(".cesium-selection-wrapper").hide();
		                    $(".infowin3D").hide();
		                }); 
		                return id;
					}
				}
			}
		};
		for(f in $cesium_utils){
			$rootScope[f] = $cesium_utils[f];
		}
		return $cesium_utils;
	}])
	.run(["$rootScope", "$cesium_utils", function($rootScope, $cesium_utils) {}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.base', ['cesium.draw','cesium.graphic','cesium.toolbar','cesium.utils']);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.locator', [])
	.factory('$cesium_locator', ["$rootScope", function($rootScope) {
		$cesium_locator = {

			// 3D的定位，依赖于2D下的arcgis的地理编码与geometry服务等
			
	        // 定位到指定名称的地址
			cesiumAddressLocator : function(name, level){
				var go = $rootScope.gisObject;
				if(!$rootScope.isNullOrUndefined(go.locator)){
					go.locatorLevel = level ? level : 8;
					$rootScope.addressToLocations(name, function(candidate) {
			            if (candidate && candidate.length>0) {
			            	var adr = candidate[0];
			                var location = adr.location;
			                var c_hegiht = 0;
			                if(go.locatorLevel<=6){
			                	c_hegiht = 2145273;
			                } else if(go.locatorLevel==7){
								c_hegiht = 1395224;
			                }else if(go.locatorLevel==8){
								c_hegiht = 672401;
			                }else if(go.locatorLevel==9){
								c_hegiht = 331095;
			                }else if(go.locatorLevel>=10){
								c_hegiht = 163759;
			                }
			                $rootScope.cesiumLocation(location,c_hegiht);
			            }
			        });
				}
			},

			// 经纬度定位
			cesiumJwdLocator : function(lonD,lonF,lonM,latD,latF,latM){
				$rootScope.deDrawAndClearGraphics();
				if (lonD > 180 || lonD < 0) {
					alert("【经度】:'度'范围 必须介于0~180之间,请重新输入");
					return;
				}
				if (latD > 90 || latD < 0) {
					alert("【纬度】:'度'范围必须介于0~90之间,请重新输入");
					return;
				}
				if (lonF > 60 || latF > 60 || lonF < 0 || latF < 0) {
					alert("'分' 范围必须介于0~60之间,请重新输入");
					return;
				}
				if (lonM > 60 || latM > 60 || lonM < 0 || latM < 0) {
					alert("'秒' 范围必须介于0~60之间,请重新输入");
					return;
				}

				var lon = $rootScope.DMSConvertToDegree(lonD, lonF, lonM);
				var lat = $rootScope.DMSConvertToDegree(latD, latF, latM);

				if (lat == "" || lon == "") {
					alert("请输入正确的经纬度");
					return;
				}

				var rPoint = new esri.geometry.Point();
				rPoint.x = lon;
				rPoint.y = lat;

				$rootScope.cesiumLocation(rPoint);
			},

			// 地理坐标定位
			cesiumDlLocator : function(x, y){
				var go = $rootScope.gisObject;
				$rootScope.deDrawAndClearGraphics();
				var rPoint = new esri.geometry.Point();
				rPoint.x = x;
				rPoint.y = y;
				$rootScope.cesiumLocation(rPoint);
			},

			// 平面坐标定位
			cesiumPmLocator : function(x, y){
				var go = $rootScope.gisObject;
				$rootScope.deDrawAndClearGraphics();
				var rPoint = new esri.geometry.Point();
				rPoint.x = x;
				rPoint.y = y;
				rPoint.spatialReference = go.tywkid;

				$rootScope.geoProject([rPoint], go.dlwkid, function(graphics){
					$rootScope.cesiumLocation(graphics[0]);
				});
			},

			// 3D定位
			cesiumLocation : function(rPoint, c_hegiht){
				var go = $rootScope.gisObject;
				var _extent = go.fullExtent;
				if (!_extent.contains(rPoint)) {
					alert("坐标信息不在范围之内");
					return;
				}

				c_hegiht = c_hegiht ? c_hegiht : Math.ceil(go.cesium.camera.positionCartographic.height);
				go.cesium.camera.flyTo({
				    destination : Cesium.Cartesian3.fromDegrees(rPoint.x, rPoint.y, c_hegiht)
				});
			}
		};
		for(f in $cesium_locator){
			$rootScope[f] = $cesium_locator[f];
		}
		return $cesium_locator;
	}]).run(["$rootScope", "$cesium_locator", function($rootScope, $cesium_locator) {}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.map.base', [])
	.factory('$cesium_map_base', ["$rootScope", function($rootScope) {
		$cesium_map_base = {

		};
		for(f in $cesium_map_base){
			$rootScope[f] = $cesium_map_base[f];
		}
		return $cesium_map_base;
	}])
	.run(["$rootScope", "$cesium_map_base", function($rootScope, $cesium_map_base) { }]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.map.layer', [])
	.factory('$cesium_map_layer', ["$rootScope", function($rootScope) {
		$cesium_map_layer = {
			
			// 天地图影像
			createTdtiImageryProvider : function(){
				var tdtImageryProvider=new Cesium.WebMapTileServiceImageryProvider({
						url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
						layer: "tdtBasicLayer",
						style: "default",
						format: "image/jpeg",
						tileMatrixSetID: "GoogleMapsCompatible",
						show: true
				});
				return tdtImageryProvider;
			},

			// 创建虚拟的地形图
			createVrTheWorldProvider : function(){
				var vrTheWorldProvider = new Cesium.VRTheWorldTerrainProvider({
				    url : 'http://www.vr-theworld.com/vr-theworld/tiles1.0.0/73/',
				    credit : 'Terrain data courtesy VT MÄK'
				});
				return vrTheWorldProvider;
			},

			// 创建arcgis地形图
			createArcGisTerrainProvider : function(){
				var terrainProvider = new Cesium.ArcGisImageServerTerrainProvider({
					  url : 'https://elevation.arcgisonline.com/ArcGIS/rest/services/WorldElevation/DTMEllipsoidal/ImageServer',
					  token : 'KED1aF_I4UzXOHy3BnhwyBHU4l5oY6rO6walkmHoYqGp4XyIWUd5YZUC1ZrLAzvV40pR6gBXQayh0eFA8m6vPg..',
					  proxy : new Cesium.DefaultProxy('/terrain/')
					});
				return terrainProvider;
			},

			// 创建本地的离线的地形服务
			createLocalTerrainProvider : function(url){
				return new Cesium.CesiumTerrainProvider({
			    	url: url
				});
			},

			// 返回stk-terrain
			createStkTerrainProvider:function(){
				return new Cesium.CesiumTerrainProvider({
				    url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
				    requestWaterMask : true, requestVertexNormals : true });
			},

			// 创建arcgis影像服务
			createArcgisImageProvider : function(url){
				return new Cesium.ArcGisMapServerImageryProvider( {  
				    url : url
				});
			},

			// 创建简单图片地图（../wdpjs/cesiumjs/baseImage.png）/
			createSingleImageryProvider : function (url){
				return new Cesium.SingleTileImageryProvider({
					url: url, show: true });
			},

			// 叠合arcgis的动态服务
			addArcGisImageryProvider:function(url,alpha){
				var ip = $rootScope.createArcgisImageProvider(url);
				var layers = $rootScope.gisObject.cesium.scene.imageryLayers;
				var slgylayer = layers.addImageryProvider(ip);
				//透明度
				if(alpha && alpha!='' && alpha!=0){
					slgylayer.alpha = alpha;
				}
				//设置图层的亮度  
				slgylayer.brightness = 1.5;
				return slgylayer;
			},

			/**
			 * 添加一个影像服务，控制影像服务显示范围
			 * @param imageryProvider 影像服务
			 * @param minlat 最小纬度
			 * @param minlon 最小经度
			 * @param maxlat 最大纬度
			 * @param maxlon 最大经度
			 */
			addImageryProviderByRectangle:function(imageryProvider,minlat,minlon,maxlat,maxlon){
				var layers = $rootScope.gisObject.cesium.scene.imageryLayers;  
				imageryProvider.rectangle=Cesium.Rectangle.fromDegrees(minlat,minlon,maxlat,maxlon); 
				//添加一个图层，在特定位置绘制一个图片  
				layers.addImageryProvider(imageryProvider);
			},

			// 设置地形服务
			setTerrainProvider : function(terrainProvider){
				$rootScope.gisObject.cesium.terrainProvider = terrainProvider;
			},

			// 设置背景地图服务
			setBaseProvider : function(provider){
				$rootScope.gisObject.cesium.imageryProvider = provider;
			},

			// 添加图层 alpha 透明度
			addCesiumLayer : function(url,mtype,alpha,s){
				var ml = null;
				if(mtype == "ArcGISTiledMapServiceLayer"){
					// 瓦片地图服务
					var p = $rootScope.createArcgisImageProvider(url);
					ml = $rootScope.gisObject.cesium.imageryLayers.addImageryProvider(p);
				} else if(mtype == "ArcGISDynamicMapServiceLayer"){
					// 动态地图服务
					ml = $rootScope.addArcGisImageryProvider(url,alpha);
				} else if(mtype == "WMSLayer"){
					
				} else if(mtype == "WMTSLayer"){
					
				} else if(mtype == "ArcGISImageServiceLayer"){
					
				} else if(mtype == "bMapVeclayer"){
					
				} else if(mtype == "bMapImglayer"){
					
				} else if(mtype == "bMapAnolayer"){
					
				} else if(mtype == "tdMapAnnoLayer"){
					
				} else if(mtype == "tdml"){
					
				} else if(mtype == "tdMapImgAnnoLayer"){
					
				} else if(mtype == "tdMapImgLayer"){
					
				} else if(mtype == "terrainLayer"){
					var p = $rootScope.createLocalTerrainProvider(url);
					$rootScope.setTerrainProvider(p);
				}
				if(ml) ml.show = s;
				return ml;
			},

			// 根据参数，初始化地图
			initCesiumLayer : function(layers){
		    	if(!layers) return;
		    	var vls = [];
		    	for(var i=layers.length-1;i>=0;i--){
		    		var layer = layers[i];
		    		if(layer.valid3D==true){
		    			vls.push(layer);
		    		}
		    	}

		    	// 将第一个设置为背景
		    	// if(vls.length<=0) return;
		    	// var go = $rootScope.gisObject;
		    	// var p = $rootScope.createArcgisImageProvider(vls[0].url);
		    	// $rootScope.setBaseProvider(p);

		    	var go = $rootScope.gisObject;
		    	go.D3LayerGroup = [];
		    	var temp3Dlayer = [];
		    	if(vls.length<=0) return;

		    	for(var i=0;i<vls.length;i++){
		    		var layer = vls[i];
		    		var ml = $rootScope.addCesiumLayer(layer.url,layer.type,layer.transparency,layer.show3D);
					if(ml!=null){
						var aItem = $rootScope.getArrayItem(temp3Dlayer,'groupname',layer.groupname);
						if(aItem==null){
							var item = {groupname:layer.groupname,layers:[ml],show:layer.show3D};
							temp3Dlayer.push(item);
						}else{
							aItem.layers.push(ml);
						}
					}
		    	}
		    	for(var i=temp3Dlayer.length-1;i>=0;i--){
		    		go.D3LayerGroup.push(temp3Dlayer[i]);
		    	}
			},

			// 获取指定分组是否展示
			get3DlayersShow:function(groupname){
				var go = $rootScope.gisObject;
				var aItem = $rootScope.getArrayItem(go.D3LayerGroup,'groupname',groupname);
				if(aItem){
					return aItem.show;
				}else{
					return false;
				}
			},

			// 设置图层是否显示
			set3DLayersShow : function(groupname, show){
				var go = $rootScope.gisObject;
				var aItem = $rootScope.getArrayItem(go.D3LayerGroup,'groupname',groupname);
				if(!aItem) return;
				show = show == null ? !aItem.show : show;
				aItem.show = show;
				aItem.layers.forEach(function(item){
					item.show = show;
				});
			}
		};
		for(f in $cesium_map_layer){
			$rootScope[f] = $cesium_map_layer[f];
		}
		return $cesium_map_layer;
	}])
	.run(["$rootScope", "$cesium_map_layer", function($rootScope, $cesium_map_layer) { }]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.map.ui', [])
	.directive('cesiumMap', ["$rootScope", "$parse", function($rootScope,$parse) {
		return {
			replace : true,
			restrict : 'E',
			template : '<div></div>',
			link : function(scope, element, attrs, ctrl) {
				var para = eval("("+attrs.para+")");
				var defaultPara = {
				};

				para = jQuery.extend(false, defaultPara, para);
				var go = $rootScope.gisObject;

		        cesiumObject.initFinshEvent= function(){
		        	var baseUrl = getCesiumBaseProvider();
		        	var imageryProvider = new Cesium.ArcGisMapServerImageryProvider( {  
					    url : baseUrl
					});
		        	// 初始化地图
		        	go.cesium = new Cesium.Viewer(attrs.id, {
						scene3DOnly: false, 
						baseLayerPicker: false,  //非控件添加地图，必须为false，不然直接报错
						imageryProvider: imageryProvider, //初始背景
						animation: false,
						fullscreenButton: false,
						geocoder: false,
						homeButton: false,
						infoBox: false,
						sceneModePicker: false,
						selectionIndicator: false,
						timeline: false,
						navigationHelpButton: false,
						navigationInstructionsInitiallyVisible: false }
					);

					var onFinshed = null;
					if(attrs.onfinshed){
						onFinshed = $rootScope[attrs.onfinshed];
						if(onFinshed){
							onFinshed();
						}
					}
		        }
			}
		};
	}]);
}(window, angular));
(function(window, angular, undefined){
	angular.module('cesium.map', ['cesium.map.base','cesium.map.layer','cesium.map.ui']);
}(window, angular));
(function(window, angular, undefined){
	angular.module('gis.cesium', ['cesium.base','cesium.locator','cesium.map']);
}(window, angular));